<?php
require_once 'config.php';

try{
	$db = new PDO('pgsql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e){
	print "Error!: " . $e->getMessage();
	die();
}

if (isset($_GET['token'])) {
	$token = $_GET['token'];
	$sql = sprintf('SELECT *  FROM "users" WHERE "TOKEN" LIKE \'%s\' AND "EXPIRATION" > CURRENT_TIMESTAMP', $token);
	$stmt = $db->query($sql)->fetch();

	if (isset($stmt['id'])) {
		$name = null;
		$surname = null;
		$id_group = 0;
		$logo = null;

		$sql = 'SELECT "TITLE", "CONTENT", "DT", "ID_USER" FROM "NEWS"';
		$stmt = $db->query($sql);
		$result = '{"news":[';
		while ($row = $stmt->fetch()) {
			$result .= sprintf('{"title": "%s", "content": "%s","date":"%s","id_user":%d},',$row['TITLE'],$row['CONTENT'],$row['DT'],$row['ID_USER']);
		}
		$result = rtrim($result, ",");
		$result .= ']}';
		echo $result;
	}
	else {
		$result = '{"error": {"text": "Неверный или просроченный токен"}}';
	}
}
else {
	$result = '{"error": {"text": "Не передан токен!"}}';
}
?>
